<?php

namespace bc\model\wc;

use bc\ar\MActiveRecord;
use bc\model\shop\ShopUserModel as EcsUser;


class AgentModel extends MActiveRecord
{
	
	/**
	 * 定义数据表
	 */
	public static function tableName()
	{
		return '{{%wc_agent}}';
	}
	
	
	/**
	 * bc_user表实体名
	 */
	protected function getUserModelName()
	{
		return EcsUser::getTableSchema()->name;
	}

	//获取真实名字、手机号码、微信昵称等信息
	public function getAgentByUser_Users($params = null)
	{
		$this->columns = "bc_wc_agent.*,ecs_users.mobile,wxch_user.nickname";
		$ar = $this->find()->select( $this->columns )->leftJoin( 'ecs_users', 'bc_wc_agent.user_id=ecs_users.user_id' )
			->leftJoin( 'wxch_user', 'ecs_users.wxid=wxch_user.wxid' );
		if(!is_null($params))
			$ar->where($params);
		return $ar->asArray()->all();
	}

	//获取当前选择的信息
	public function getPresentInfo($id)
	{
		if($id)
			$params['id'] = $id;
		$data = $this->getAgentByUser_Users($params);
		foreach($data as $v){
			if( $id == $v['id'] )
				return $v;
		}
	}

	//获取二维码信息
	public function getAgentInfo($id)
	{
		if($id)
			$params['id'] = $id;
		$agentData = $this->getAgentByUser_Users($params);
		foreach($agentData as $v){
			if($v['id'] == $id){
				return $v['nickname'];
			}
		}
	}

	/**
	 * @param array $params
	 * @param string $page
	 * @param string $pageSize
	 */
	public function getList($params, $page = null, $pageSize = null)
	{
		$ar = $this->find ()->select ( $this->columns )->leftJoin ( $this->getUserModelName(), self::getTableSchema ()->name . '.user_id=' . $this->getUserModelName() . '.user_id' );
		if ($params)
		{
			$ar->where ( $params );
		}
		if ($page && $pageSize)
		{
			$offset = $this->getOffset ( $page, $pageSize );
			$ar->offset ( $offset )->limit ( $pageSize );
		}
		 
		return $ar->asArray ()->all ();
	}


	/**
	 * 统计页数
	 * @param string|array $condition
	 */
	public function getTotal($condition)
	{
		if(!empty($condition))
		{
			$ar = $this->find ()->select ( $this->columns )->leftJoin ( $this->getUserModelName(), self::getTableSchema ()->name . '.user_id=' . $this->getUserModelName() . '.user_id' );
			if ($condition)
			{
				$ar->where ( $condition );
			}
			return $ar->count();
		}
		else
			return 0;
	}

	//查找所以记录
	public function getAgentById( $id )
	{
		$where = '(user_id='.$id.' and reply_status=0) OR (user_id='.$id.' and reply_status=1)';
		$ar = $this->find()->select( $this->columns )->where( $where );
		return $ar->asArray()->all();
	}
}
